from threading import Thread, Lock
from multiprocessing import Process, Lock
from multiprocessing import Queue

def save_to_file(index, lock):
    with lock: # 1.多进程互斥锁
        with open("test.log", "a", encoding="utf-8") as f:
            f.write(str(index) + "\n")

if __name__ == "__main__":
    process_array1 = []
    lock = Lock()
    for i in range(10):
        p = Process(target=save_to_file, args=(i, lock))
        process_array1.append(p)
        p.start()
    for p in process_array1:
        p.join()
    print("done!")

# 2.线程加互斥锁
zero = 0
lock = Lock()
def foo():
    global zero
    for i in range(10**6):
        with lock:
            zero += 1
            zero -= 1

process_array2 = []
my_queue = Queue()
for i in range(2):
    p = Thread(target=foo)
    process_array2.append(p)
    p.start()
for p in process_array2:
    p.join()

print(zero)

# 3.多线程通过Queue来实现进程通信
def save_to_queue(index, my_queue):
    my_queue.put(index)

process_array3 = []
my_queue = Queue()
for i in range(10):
    p = Process(target=save_to_queue,args=(i, my_queue))
    process_array3.append(p)
    p.start()
for p in process_array3:
    p.join()

while True:
    print(my_queue.get())